package com.huawei.hms.framework.network.restclient.hwhttp.cronet;

import android.os.Build.VERSION;
import android.text.TextUtils;
import com.huawei.hms.framework.common.CreateFileUtil;
import com.huawei.hms.framework.common.IoUtils;
import com.huawei.hms.framework.common.Logger;
import com.huawei.hms.framework.network.restclient.conf.ConfCallBack;
import com.huawei.hms.framework.network.restclient.conf.ConfManager;
import com.huawei.hms.framework.network.restclient.conf.ConfParams;
import com.huawei.hms.framework.network.restclient.conf.MatcherParams.Builder;
import com.huawei.hms.framework.network.util.ContextUtil;
import com.huawei.hms.framework.network.util.HttpUtils;
import com.huawei.hms.quic.HmsCronetException;
import com.huawei.hms.quic.HmsCronetLoader;
import com.huawei.hms.quic.HmsCronetLoader.HmsCronetLoadCallBack;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.json.JSONObject;

public class CronetNegotiateManager {
    private static final int BUFFER_SIZE = 5242880;
    private static final String CONF_MANAGER_CLASS = "com.huawei.hms.framework.network.restclient.conf.ConfManager";
    private static final String CRONET_ENGINE_CLASS = "org.chromium.net.CronetEngine";
    private static final String EMPTY_STRING = "";
    private static final String HMS_QUIC_LOADER_CLASS = "com.huawei.hms.quic.HmsCronetLoader";
    private static final int INIT_LODDED_FAIL = 3;
    private static final int INIT_LODDED_SUCCESS = 2;
    private static final int INIT_LODING = 1;
    private static final int INIT_UNKNOWN = 0;
    private static final int MAX_SIZE = 8192;
    private static final String TAG = "CronetNegotiateManager";
    private static volatile CronetNegotiateManager instance;
    private int initHmsQuicProviderState = 0;
    private boolean isRunning;
    private ConcurrentHashMap<String, QuicHint> quicHintMap = new ConcurrentHashMap();

    class QuicConfCallBack implements ConfCallBack {
        QuicConfCallBack() {
        }

        public void onResponse(String str) {
            CronetNegotiateManager.getInstance().loadQuicCacheFromLocal(str);
        }
    }

    public static CronetNegotiateManager getInstance() {
        if (instance == null) {
            synchronized (CronetNegotiateManager.class) {
                if (instance == null) {
                    instance = new CronetNegotiateManager();
                }
            }
        }
        return instance;
    }

    public Boolean isEnableQuic(String str, int i) {
        Logger.v(TAG, "isEnableQuic is execute,and the map is: %s", this.quicHintMap.keySet().toString());
        QuicHint quicHint = (QuicHint) this.quicHintMap.get(str);
        if (quicHint == null || !quicHint.getEnableQuic() || (i != -1 && i != quicHint.getPort())) {
            return Boolean.valueOf(false);
        }
        Logger.v(TAG, "use cronet and request");
        return Boolean.valueOf(true);
    }

    public void updateQuicHints(String str, int i, boolean z) {
        if (!(str == null || z)) {
            this.quicHintMap.remove(str);
        }
        QuicHint quicHint = (QuicHint) this.quicHintMap.get(str);
        if (quicHint == null || !(i == -1 || i == quicHint.getPort())) {
            Logger.v(TAG, "server negotiate port is %d, but there is not compatible config or historical success record", Integer.valueOf(i));
        } else {
            Logger.v(TAG, "the host:%s will use cronet next time", str);
            quicHint.setEnableQuic(z);
        }
        Logger.i(TAG, "updateQuicHints is execute,and the map is: %s", this.quicHintMap.keySet().toString());
    }

    private void initHmsQuicLoader() {
        HmsCronetLoader.asyncInit(ContextUtil.getContext(), new HmsCronetLoadCallBack() {
            public void onSuccess() {
                CronetNegotiateManager.this.initHmsQuicProviderState = 2;
            }

            public void onFail(Exception exception) {
                CronetNegotiateManager.this.initHmsQuicProviderState = 3;
                if (exception instanceof HmsCronetException) {
                    Logger.i(CronetNegotiateManager.TAG, "Init Hms Quic Loader failed, reason:" + exception.getMessage());
                } else if (exception instanceof IllegalArgumentException) {
                    Logger.i(CronetNegotiateManager.TAG, "invalid argument, reason:" + exception.getMessage());
                }
            }
        });
    }

    public void lazyInitHmsQuicLoader() {
        synchronized (this) {
            if (this.initHmsQuicProviderState != 0) {
                Logger.i(TAG, "run lazyInitHmsQuicLoader before");
                return;
            }
            try {
                Class.forName(HMS_QUIC_LOADER_CLASS);
                this.initHmsQuicProviderState = 1;
                initHmsQuicLoader();
            } catch (ClassNotFoundException e) {
                Logger.w(TAG, "load com.huawei.hms.quic.HmsCronetLoaderclass failed, exception:%s", e.getClass().getSimpleName());
                this.initHmsQuicProviderState = 3;
            }
        }
    }

    private boolean isPackageConfigSDK() {
        try {
            Class.forName(CONF_MANAGER_CLASS);
            return true;
        } catch (ClassNotFoundException e) {
            Logger.i(TAG, "load com.huawei.hms.framework.network.restclient.conf.ConfManagerclass failed, exception:%s", e.getClass().getSimpleName());
            return false;
        }
    }

    public void loadQuicConf() {
        if (isPackageConfigSDK()) {
            Logger.i(TAG, "begin to loading the config file!");
            synchronized (this) {
                if (this.isRunning) {
                    Logger.w(TAG, "the process is running,and you shouldn't execute it once!");
                    return;
                }
                this.isRunning = true;
                ConfManager.getInstance().getAsynConfig(new ConfParams(ConfManager.getDefaultConfigID(ContextUtil.getContext()), new Builder().enableSdkVersion(true).enableGradID(true).build(), null), new QuicConfCallBack());
            }
        }
    }

    private void loadQuicCacheFromLocal(String str) {
        Object readQuicConfigFile;
        Object e;
        try {
            readQuicConfigFile = readQuicConfigFile(str);
            try {
                Logger.v(TAG, "load Quic config info success.");
            } catch (IOException e2) {
                e = e2;
                Logger.w(TAG, "read local Quic cache occur error, exception:%s", e.getClass().getSimpleName());
                if (TextUtils.isEmpty(readQuicConfigFile)) {
                    loadConfigToCache(readQuicConfigFile);
                } else {
                    Logger.v(TAG, "configInfo is null or empty.");
                }
            }
        } catch (IOException e3) {
            IOException iOException = e3;
            readQuicConfigFile = null;
            e = iOException;
            Logger.w(TAG, "read local Quic cache occur error, exception:%s", e.getClass().getSimpleName());
            if (TextUtils.isEmpty(readQuicConfigFile)) {
                loadConfigToCache(readQuicConfigFile);
            } else {
                Logger.v(TAG, "configInfo is null or empty.");
            }
        }
        if (TextUtils.isEmpty(readQuicConfigFile)) {
            loadConfigToCache(readQuicConfigFile);
        } else {
            Logger.v(TAG, "configInfo is null or empty.");
        }
    }

    private String readQuicConfigFile(String str) throws IOException {
        String str2 = "";
        if (TextUtils.isEmpty(str)) {
            return str2;
        }
        File newFile = CreateFileUtil.newFile(str);
        if (newFile.exists() && newFile.isFile()) {
            return readFromPath(str);
        }
        return str2;
    }

    private String readFromPath(String str) throws IOException {
        InputStream newFileInputStream;
        Reader inputStreamReader;
        Throwable e;
        InputStream inputStream;
        Reader reader;
        Reader reader2;
        InputStream inputStream2 = null;
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        try {
            newFileInputStream = CreateFileUtil.newFileInputStream(str);
            try {
                inputStreamReader = new InputStreamReader(newFileInputStream, "UTF-8");
            } catch (IOException e2) {
                e = e2;
                inputStreamReader = null;
                inputStream = newFileInputStream;
                reader = null;
                inputStream2 = inputStream;
                try {
                    Logger.e(TAG, "this method readToBuffer occur error.", e);
                    throw e;
                } catch (Throwable th) {
                    e = th;
                    reader2 = reader;
                    newFileInputStream = inputStream2;
                    IoUtils.closeSecure(reader2);
                    IoUtils.closeSecure(inputStreamReader);
                    IoUtils.closeSecure(newFileInputStream);
                    throw e;
                }
            } catch (Throwable th2) {
                e = th2;
                inputStreamReader = null;
                reader2 = null;
                IoUtils.closeSecure(reader2);
                IoUtils.closeSecure(inputStreamReader);
                IoUtils.closeSecure(newFileInputStream);
                throw e;
            }
            try {
                reader2 = new BufferedReader(inputStreamReader);
                try {
                    StringBuilder stringBuilder = new StringBuilder();
                    char[] cArr = new char[MAX_SIZE];
                    for (int read = reader2.read(cArr); read > 0; read = reader2.read(cArr)) {
                        stringBuilder.append(new String(cArr, 0, read));
                        if (stringBuilder.length() > BUFFER_SIZE) {
                            Logger.e(TAG, "readFromPath failed,file content is very big.");
                            String str2 = "";
                            IoUtils.closeSecure(reader2);
                            IoUtils.closeSecure(inputStreamReader);
                            IoUtils.closeSecure(newFileInputStream);
                            return str2;
                        }
                    }
                    IoUtils.closeSecure(reader2);
                    IoUtils.closeSecure(inputStreamReader);
                    IoUtils.closeSecure(newFileInputStream);
                    return stringBuilder.toString();
                } catch (IOException e3) {
                    e = e3;
                    inputStream2 = newFileInputStream;
                    reader = reader2;
                } catch (Throwable th3) {
                    e = th3;
                }
            } catch (IOException e4) {
                e = e4;
                inputStream = newFileInputStream;
                reader = null;
                inputStream2 = inputStream;
                Logger.e(TAG, "this method readToBuffer occur error.", e);
                throw e;
            } catch (Throwable th4) {
                e = th4;
                reader2 = null;
                IoUtils.closeSecure(reader2);
                IoUtils.closeSecure(inputStreamReader);
                IoUtils.closeSecure(newFileInputStream);
                throw e;
            }
        } catch (IOException e5) {
            e = e5;
            inputStreamReader = null;
            reader = null;
            Logger.e(TAG, "this method readToBuffer occur error.", e);
            throw e;
        } catch (Throwable th5) {
            e = th5;
            inputStreamReader = null;
            newFileInputStream = null;
            reader2 = null;
            IoUtils.closeSecure(reader2);
            IoUtils.closeSecure(inputStreamReader);
            IoUtils.closeSecure(newFileInputStream);
            throw e;
        }
    }

    private void loadConfigToCache(String str) {
        Logger.v(TAG, "the configInfo is %s", str);
        try {
            JSONObject jSONObject = new JSONObject(str).getJSONObject("networkkit").getJSONObject("networkkit_quic").getJSONObject("services");
            Iterator keys = jSONObject.keys();
            while (keys.hasNext()) {
                String str2 = (String) keys.next();
                Object string = jSONObject.getString(str2);
                if (TextUtils.isEmpty(str2) || TextUtils.isEmpty(string)) {
                    Logger.e(TAG, "config file has been broken.");
                } else {
                    try {
                        if (Integer.valueOf(string).intValue() == 1) {
                            addQuicHint(str2);
                        }
                    } catch (NumberFormatException e) {
                        Logger.w(TAG, "the string cannot be parsed as an integer,you should check the file");
                    }
                }
            }
            Logger.v(TAG, "loadConfigToCache is execute,and the map size is:%s---%s", Integer.valueOf(this.quicHintMap.size()), this.quicHintMap.keySet().toString());
        } catch (Throwable e2) {
            Logger.w(TAG, "parse JSON occur error.", e2);
        }
    }

    public void addQuicHint(String str) {
        if (TextUtils.isEmpty(str)) {
            Logger.e(TAG, "invalid argument");
            return;
        }
        String str2;
        if (HttpUtils.isHttpUrl(str)) {
            str2 = str;
        } else {
            str2 = "https://" + str;
        }
        try {
            QuicHint quicHint;
            URL url = new URL(str2);
            QuicHint quicHint2 = (QuicHint) this.quicHintMap.get(url.getHost());
            if (quicHint2 == null) {
                quicHint2 = new QuicHint();
                quicHint2.setHost(url.getHost());
                quicHint = quicHint2;
            } else {
                quicHint = quicHint2;
            }
            quicHint.setPort(url.getPort() == -1 ? 443 : url.getPort());
            Logger.w(TAG, "QuicHit:" + quicHint);
            this.quicHintMap.put(quicHint.getHost(), quicHint);
        } catch (MalformedURLException e) {
            Logger.e(TAG, "add QuicHit failed，please check domian format:" + str);
        }
    }

    public void addQuicHint(List<String> list) {
        if (list == null) {
            Logger.e(TAG, "invalid argument");
            return;
        }
        for (String addQuicHint : list) {
            addQuicHint(addQuicHint);
        }
    }

    public ConcurrentHashMap<String, QuicHint> getQuicHints() {
        return this.quicHintMap;
    }

    public boolean isSupportCronet() {
        if (VERSION.SDK_INT < 24) {
            Logger.w(TAG, "the android version is lower[API%d] than API%d, disable quic", Integer.valueOf(VERSION.SDK_INT), Integer.valueOf(24));
            return false;
        }
        try {
            Class.forName(CRONET_ENGINE_CLASS);
            return true;
        } catch (ClassNotFoundException e) {
            Logger.w(TAG, "load network-quic CronetEngine class failed, exception:%s", e.getClass().getSimpleName());
            return false;
        }
    }

    public boolean isAvaliable() {
        return this.initHmsQuicProviderState == 2;
    }
}
